﻿using System.ServiceModel.Syndication;

namespace Jacobi.Seesmic.FeedReader.Model
{
    /// <summary>
    /// A factory to create <see cref="FeedSource"/> instances based on a <see cref="FeedInfo"/>.
    /// </summary>
    internal sealed class FeedManagerFactory
    {
        /// <summary>
        /// Constructs a new instance.
        /// </summary>
        /// <param name="dataProvider">Must not be null.</param>
        public FeedManagerFactory(DataProvider dataProvider)
        {
            DataProvider = dataProvider;
        }

        /// <summary>
        /// Gets the <see cref="DataProvider"/> this instance was constructed with.
        /// </summary>
        public DataProvider DataProvider { get; private set; }

        /// <summary>
        /// Creates for each <see cref="FeedInfo"/> in <paramref name="feedInfos"/>
        /// a corresponding <see cref="FeedSource"/> and <see cref="FeedManager"/> instance.
        /// </summary>
        /// <param name="feedInfos">Must not be null.</param>
        /// <returns>Never returns null.</returns>
        public FeedManagerCollection CreateAll(FeedInfoCollection feedInfos)
        {
            var feedManagers = new FeedManagerCollection();

            foreach (var feedInfo in feedInfos)
            {
                var feedManager = CreateFeedManager(feedInfo);

                if (feedManager != null)
                {
                    feedManagers.Add(feedManager);
                }
            }

            return feedManagers;
        }

        /// <summary>
        /// Creates a new <see cref="FeedSource"/> instance for the specified <paramref name="feedInfo"/>.
        /// </summary>
        /// <param name="feedInfo">Must not be null.</param>
        /// <returns>Returns an instance of either the <see cref="Atom10FeedSource"/> or the <see cref="Rss20FeedSource"/> class.</returns>
        public static FeedSource CreateFeedSource(FeedInfo feedInfo)
        {
            switch (feedInfo.FeedType)
            {
                case SyndicationVersions.Rss20:
                    return new Rss20FeedSource(feedInfo);
                case SyndicationVersions.Atom10:
                    return new Atom10FeedSource(feedInfo);
            }

            return null;
        }

        /// <summary>
        /// Creates a <see cref="FeedSource"/> as well as the <see cref="FeedManager"/>
        /// </summary>
        /// <param name="feedInfo">Must not be null.</param>
        /// <returns>Returns null when the <see cref="FeedSource"/> could not be created.</returns>
        public FeedManager CreateFeedManager(FeedInfo feedInfo)
        {
            var feedSource = CreateFeedSource(feedInfo);

            if (feedSource != null)
            {
                return new FeedManager(DataProvider, feedInfo, feedSource);
            }

            return null;
        }
    }
}